package com.why.whyoj.judge.codesanbox.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.why.whyoj.common.ErrorCode;
import com.why.whyoj.exception.BusinessException;
import com.why.whyoj.judge.codesanbox.CodeSandBox;
import com.why.whyoj.judge.codesanbox.CodeSandBox;
import com.why.whyoj.judge.codesanbox.model.ExecuteCodeRequest;
import com.why.whyoj.judge.codesanbox.model.ExecuteCodeResponse;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Component
@Data
public class RemoteCodeSandbox implements CodeSandBox {
    @Value("${codesandbox.url: http://192.168.64.129:8090/executeCode}")
    public String url;

    private static String AUTH_REQUEST_HEADER = "secretHeader";

    private static String AUTH_REQUEST_SECRET = "asjdlkfjlaksalsfkj123123jlkj";
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        System.out.println("远程代码沙箱");
        String url = "http://192.168.88.121:8090/executeCode";
        String jsonStr = JSONUtil.toJsonStr(executeCodeRequest);
        String responseStr = HttpUtil.createPost(url).header(AUTH_REQUEST_HEADER, AUTH_REQUEST_SECRET).body(jsonStr).execute().body();
        if (StringUtils.isBlank(responseStr)) {
            throw new BusinessException(ErrorCode.CODE_SANDBOX_ERROR, "远程代码沙箱返回空值");
        }
        return JSONUtil.toBean(responseStr, ExecuteCodeResponse.class);
    }
}
